//
//  SCPhotoBrowserController.swift
//  GZWeibo007
//
//  Created by newuser on 15/12/30.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD


class SCPhotoBrowserController: UIViewController {

    //MARK: - 属性
    
    //cell间距
    private let cellMargin: CGFloat = 10

    ///选中的indexPath
    private var selectedIndexPath: NSIndexPath
    ///大图数组
    private var models: [SCPhotoBrowserModel]
    
    //流水
    private let layou = UICollectionViewFlowLayout()
    
    /// 重用表示
    private let ReuseIdentifier = "ReuseIdentifier"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //构造方法
    init(indexPath:NSIndexPath, models: [SCPhotoBrowserModel]) {
        self.selectedIndexPath = indexPath
        self.models = models
        super.init(nibName: nil, bundle: nil)
    }

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
        //设置页码
        pageLabel.text = "5 / 9"
        
        view.backgroundColor = UIColor.clearColor()
        
       
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        //设置页码
        setPageNum(selectedIndexPath.item + 1)
    }
    
    private func setPageNum(currnetPage: Int) {
        pageLabel.text = "\(currnetPage) / \(models.count)"
    }
    
    
    
    ///准备ui
    func prepareUI() {
    
        //添加自控制器
        view.addSubview(bkgView)
        view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        //添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        
        bkgView.frame = view.bounds
        
        collectionView.frame = CGRectMake(0, 0, view.bounds.width + cellMargin, view.bounds.height)
    
        
        
        //collection填充父控件
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        //页码
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        //关闭
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb" : closeButton]))
        //保存
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sb" : saveButton]))
    //水平方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb" : closeButton, "sb" : saveButton]))
    
        setupCollection()
    }
    
    ///设置collectionView
    func setupCollection() {
       //注册cell
        collectionView.registerClass(SCPhotoBrowserCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        layou.itemSize = UIScreen.mainScreen().bounds.size
        //设置水平
        layou.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
        
        //间距
        layou.minimumInteritemSpacing = cellMargin
        layou.minimumLineSpacing = cellMargin
        
        //取消弹簧
        collectionView.bounces = false
        
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: cellMargin)
        
        collectionView.backgroundColor = UIColor.clearColor()
    }
    
    //MARK: - 点击事件
    func close() {
       dismissViewControllerAnimated(true, completion: nil)
    }
    ///保存图片-->到相册
    func save() {
        //获取正在显示的cell
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! SCPhotoBrowserCell
        //获取增长显示的image
        if let image = cell.imageView.image {
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }else {
           SVProgressHUD.showErrorWithStatus("没有图片")
        }
    }
    
    ///保存图片后回调
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
          SVProgressHUD.showErrorWithStatus("保存图片失败")
        }else {
        
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    //MARK: - 懒加载
    ///collectionView
     lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layou)
    
    //显示页数的label
    private lazy var pageLabel: UILabel = UILabel(color: UIColor.whiteColor(), fontSize: 13)
 
    //取消按钮
    private lazy var closeButton: UIButton = {
       let button = UIButton()
        //设置文字
        button.setTitle("关闭", forState: UIControlState.Normal)
        button.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        return button
    
    }()
    
    ///保存按钮
    private lazy var saveButton: UIButton = {
    
        let button = UIButton()
        
        button.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        //设置文字
        button.setTitle("保存", forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        return button
    }()
    
    
    ///背景视图
    private lazy var bkgView: UIView = {
    
        let view = UIView()
        view.backgroundColor = UIColor.blackColor()
    
        return view
    }()
    
}

//MARK: - collection数据源扩展
extension SCPhotoBrowserController: UICollectionViewDataSource,UICollectionViewDelegate {

    //返回数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models.count
    }
    
    //返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! SCPhotoBrowserCell
        
        //设置背景
        cell.backgroundColor = UIColor.clearColor()
        
        let model = models[indexPath.item]
        
        
        //将图片传过去
        cell.imageURL = model.largeURl
        
        cell.cellDelegate = self
        
        return cell
    }
    
    //监听cell滚动
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        selectedIndexPath = collectionView.indexPathsForVisibleItems().first!
        
        let index = Int(scrollView.contentOffset.x / scrollView.frame.width)
        
        //重新设置页数
        setPageNum(index + 1)
    }
}

//实现cell的缩放的协议
extension SCPhotoBrowserController: SCPhotoBrowserCellDelegate {

//返回view让cell修改
    func viewForTransparent() -> UIView {
        return bkgView
    }
    
    func cellForDismissController() {
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    func targetRectForDismissController() -> CGRect {
        return dismissTargetRect()
    }
    
}



//扩展实现转场动画代理
extension SCPhotoBrowserController: UIViewControllerTransitioningDelegate { 
    // 返回一个控制modal的动画对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SCPhotoBrowserModalAnimation()
    }
    
    //返回退出动画
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SCPhotoBrowserDismissedAnimation()
    }
    
}

//扩展转场动画
extension SCPhotoBrowserController {

    ///生成model的过渡视图
    func modalTempImageView() -> UIImageView {
    
        //创建过渡视图
        let tempImageView = UIImageView()
        
        //获取对应的模型
        let model = models[selectedIndexPath.item]
        
        //获取缩略图
        let imageView = model.imageView!
        
        //设置过渡视图image
        tempImageView.image = imageView.image
        
        //设置缩放模式
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
    
        tempImageView.clipsToBounds = true
        
        //坐标系转换
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        //设置frame
        tempImageView.frame = newFrame
        
        return tempImageView
    }

    ///计算model的最终位置
    func modelTargetRect() -> CGRect {
    //计算小图,新浪照片等比例
        let model = models[selectedIndexPath.item]
        
        //获取缩略图.不能强制拆包
        if let image = model.imageView?.image {
        
            let newWidth = UIScreen.mainScreen().bounds.width
            //新高度 /新宽度 = 老高度/老宽度
            let newHeight = newWidth * image.size.height / image.size.width
            
            var offsetY:CGFloat = 0
            
            //判断长图
            if newHeight < UIScreen.mainScreen().bounds.height {
            
                //短图
                offsetY = (UIScreen.mainScreen().bounds.height - newHeight) * 0.5

            } else {
            
            }
            return CGRect(x: 0, y: offsetY, width: newWidth, height: newHeight)
        }
    
       return CGRectZero
    }
   
    //dismiss是得过渡视图
    func dismissTempImageView() -> UIImageView {
    
    
        //创建过渡视图
        let tempImageView = UIImageView()
        
        //获取在正显示的cell
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! SCPhotoBrowserCell
        
        //获取正在显示的image
        if let image = cell.imageView.image {
        
          //设置过渡视图的image
            tempImageView.image = image
            
            //设置过渡视图的frame
            let newFrame = cell.imageView.superview!.convertRect(cell.imageView.frame, toCoordinateSpace: view)
            tempImageView.frame = newFrame
            
            //设置填充模式
            tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
            tempImageView.clipsToBounds = true
        }
        return tempImageView
    }
    
    ///返回dismiss是得目标frame
    func dismissTargetRect() -> CGRect {
    
        //获取到对应的模型
        let model = models[selectedIndexPath.item]
        
        //获取缩略图
        let imageView = model.imageView!
        
        //转换坐标系.从imageView的父控件的屏幕左上角
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
    
        return newFrame
    }
    
}
